package HomeService

import (
	"context"
	"database/sql"
	"gdshop-back-end-go/client-api/app/request/HomeReq"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/entity"
	"gdshop-back-end-go/common/libs/clickCaptcha"
	"gdshop-back-end-go/common/response"
	"gdshop-back-end-go/common/tools"
	"github.com/gogf/gf/frame/g"
)

func SendVCode(ctx context.Context, parames *HomeReq.SendVCode) *response.JsonResponse {
	// 短信验证码发送必须人机验证
	if parames.CaptchaKey == "" || parames.CaptchaDots == "" {
		return response.FailByRequestMessageData(nil, "需要人机验证", g.Map{
			"need_captcha": true,
		})
	}
	// 验证人机验证
	check, err := clickCaptcha.CaptchaCheck(ctx, parames.CaptchaKey, parames.CaptchaDots)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	if !check {
		return response.FailByRequestMessage(nil, "人机验证失败")
	}

	if tools.CheckVCodeOften(parames.Mobile) {
		// true 不能发送
		return response.FailByRequestMessage(nil, "发送验证码太频繁")
	}

	memberDb := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "member")
	memberModel := (*entity.Member)(nil)
	err = memberDb.Where(g.Map{
		"mobile": parames.Mobile,
	}).Struct(&memberModel)
	// 根据场景进行判断
	switch parames.Scene {
	case "login":
		// 验证码登陆，账号不存在，报错
		if err != nil {
			if err == sql.ErrNoRows {
				return response.FailByRequestMessage(nil, "账号不存在")
			}
			return response.FailByRequestMessage(nil, err.Error())
		}
		break
	case "forget", "mod_pass":
		// 找回密码，修改密码，账号不存在，报错
		if err != nil {
			if err == sql.ErrNoRows {
				return response.FailByRequestMessage(nil, "账号不存在")
			}
			return response.FailByRequestMessage(nil, err.Error())
		}
		break
	case "reg":
		// 注册，用户如存在，报错
		if err != nil && err != sql.ErrNoRows {
			return response.FailByRequestMessage(nil, err.Error())
		}
		if memberModel != nil {
			return response.FailByRequestMessage(nil, "当前账号已存在")
		}

		break
	}

	vcode := tools.GetVCode(parames.Mobile)

	// 发送短信SDK

	tools.SetVCodeOften(parames.Mobile)

	return response.SuccessByRequestMessage(nil, "验证码已发送请注意查收"+vcode)
}
